package game.leon.war.node.handler;

import com.google.protobuf.GeneratedMessage;
import com.google.protobuf.InvalidProtocolBufferException;
import game.leon.engine.net.codec.GateRawMessage;
import game.leon.engine.utils.LinkedNode;
import game.leon.war.node.handler.letter.NodeLetter;
import org.apache.log4j.Logger;

/**
 * User: bianpeng
 * Date: 12-1-31
 */
class HandlerSuite {
    private Logger logger = Logger.getLogger(getClass());
    private LinkedNode<Handler<Object, GeneratedMessage>> funList;
    private Builder builder;
    public HandlerSuite(Builder builder) {
        this.builder = builder;
    }
    private GeneratedMessage exec(long userId, Object vo) {
        GeneratedMessage result = null;
        LinkedNode<Handler<Object, GeneratedMessage>> node = funList;
        while (node != null) {
            result = node.getItem().exec(userId, vo);
            node = node.getNext();
        }
        return result;
    }
    public void add(Handler<Object, GeneratedMessage> fun) {
        funList = LinkedNode.cons(fun, funList);
    }
    public GeneratedMessage handle(GateRawMessage message) {
        try {
            GeneratedMessage vo = (GeneratedMessage) builder.builder().mergeFrom(message.getData()).build();
            return exec(message.getUserId(), vo);
        } catch (InvalidProtocolBufferException e) {
            logger.error("unserialize failed", e);
            return null;
        }
    }
    public GeneratedMessage handle(NodeLetter letter) {
        return exec(letter.getUserId(), letter);
    }
}
